<template>
  <section class="todoapp">
    <TodoHeader @addTodo="addTodo"></TodoHeader>
    <TodoMain
      :todoList="filterTodoList"
      :isAllDone="isAllDone"
      @changeTodoStatus="changeTodoStatus"
      @delTodo="delTodo"
      @changeAllChecked="changeAllChecked"
      @changeIsEdit="changeIsEdit"
      @endTodo="endTodo"
    ></TodoMain>
    <TodoFooter
      :todoList="todoList"
      @changeVisibility="changeVisibility"
      @delAllDone="delAllDone"
      :unDoneNumber="unDoneNumber"
      :visibility="visibility"
    ></TodoFooter>
  </section>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import useLocalStoage from "../../../hooks/useLocalStoage";
import TodoHeader from "./TodoHeader.vue";
import TodoMain from "./TodoMain.vue";
import TodoFooter from "./TodoFooter.vue";

// let todoList = reactive([
//   {
//     id: "01",
//     text: "学习vue3",
//     done: true,
//     isEdit: false,
//   },
//   {
//     id: "02",
//     text: "学习react",
//     done: false,
//     isEdit: false,
//   },
// ]);
let todoListDate = useLocalStoage("todoList").value || [];
let todoList = reactive(todoListDate);

let visibility = ref("all");

// 根据todolist 和 visibility 得到一个新的todolist
let filterTodoList = computed(() => {
  if (visibility.value === "all") {
    return todoList;
  } else if (visibility.value === "active") {
    return todoList.filter((item) => item.done === false);
  } else {
    return todoList.filter((item) => item.done === true);
  }
});

// 统计没有完成的todo的个数
let unDoneNumber = computed(() => {
  return todoList.filter((item) => item.done === false).length;
});

// 删除todo
let delTodo = (idx) => {
  todoList.splice(idx, 1);
};

// 改变单个todo的状态
let changeTodoStatus = (idx, flag) => {
  todoList[idx].done = flag;
};

// 判断所有的todo是否都已完成
let isAllDone = computed(() => {
  return todoList.every((item) => item.done == true);
});

// 实现全选与全不选
let changeAllChecked = (flag) => {
  todoList.forEach((item) => {
    item.done = flag;
  });
};

// 双击修改是否处理编辑状态
let changeIsEdit = (idx) => {
  todoList[idx].isEdit = true;
};

// 结束编辑
let endTodo = (idx, text) => {
  // console.log(idx, text);
  todoList[idx].text = text.trim();
  todoList[idx].isEdit = false;
};

// 添加todo
let addTodo = (text) => {
  todoList.push({
    id: Date.now(),
    text: text,
    done: false,
    isEdit: false,
  });
};

// 修改visibility
let changeVisibility = (flag) => {
  visibility.value = flag;
};

// 删除已完成
let delAllDone = () => {
  let res = todoList.filter((item) => item.done === false);
  todoList.length = 0;
  todoList.push(...res);
};

// 监听todolist
watch(todoList, (newTodoList) => {
  useLocalStoage("todoList", newTodoList);
});
</script>
